import React, {
    cloneElement
} from 'react';

//component



export default class view extends React.Component {
    static propTypes = {
        value: React.PropTypes.any.isRequired,
        children: React.PropTypes.node.isRequired,
        onChange: React.PropTypes.func.isRequired
    };

    static defaultProps = {
        value: '',
    }
    constructor(props, context) {

        super(props, context);
        // init state;
        this.state = {
            value: props.value
        };

    }
    componentWillMount() {
        this._isMounted = true;
    }

    componentDidMount() {

    }

    componentWillReceiveProps({ value }) {
        this.setState({
            value
        });
    }

    componentWillUnmount() {
        this._isMounted = false;

    }

    getSelected(value) {
        return this.state.value == value;
    }

    getItems() {
        return this.props.children.map((item, index) => {
            return cloneElement(item, {
                key: index,
                selected: this.getSelected(item.props.value),
                onSelectClick: (value, label) => { this.handleSelectedClick(value, label, index); }
            });
        });
    }

    handleSelectedClick = (value, label, index) => {
        this.setState({
            value
        });
        this.props.onChange && this.props.onChange({ value, label, index });
    }

    render() {
        return (
            <div className="orin-sw-resegments-root" >
                { this.getItems() }
            </div>
        );
    }
}
